<template>
	<view class="container pageBg">
		<custom-nav-bar title="和50强打过官司,你问吧"></custom-nav-bar>
		<scroll-view ref="chatBoxRef" scroll-y="true" class="chat-box">
			<view v-for="(message, index) in messages" :key="index" class="message">
				<text :class="{'user-message': message.type === 'user', 'server-message': message.type === 'server'}"
					decode>
					{{ message.content }}
				</text>
			</view>
			<!-- 显示临时消息内容 -->
			<text v-if="tempMessage" class="message server-message" decode>
				{{ tempMessage }}
			</text>
		</scroll-view>

		<view class="input-container">
			<input class="input-box" type="text" v-model="inputMessage" placeholder="输入消息" />
			<button class="send-button" @click="sendMessage">发送</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		nextTick
	} from 'vue';

	const chatBoxRef = ref(null);
	const ws = ref(null);
	const messages = ref([]);
	const tempMessage = ref(''); // 用于存储临时消息内容

	const inputMessage = ref('');
	const socketConnected = ref(false);
	const reconnectAttempts = ref(0); // 记录重连次数

	const scrollToBottom = () => {
		// 如果有 chatBoxRef 且里面有内容
		if (chatBoxRef.value) {
			chatBoxRef.value.scrollTo({
				top: chatBoxRef.value.scrollHeight,
				behavior: 'smooth'
			});
		}
	};


	const initWebSocket = () => {
		ws.value = uni.connectSocket({
			url: 'wss://riddle.miyucaicai.cn/chat/coze',
			success: () => {
				console.log('WebSocket连接成功');
			}
		});

		ws.value.onOpen((res) => {
			console.log('WebSocket已连接', res);
			socketConnected.value = true;
			reconnectAttempts.value = 0; // 重置重连次数
		});

		ws.value.onMessage((res) => {
			console.log('收到消息', res);
			const data = JSON.parse(res.data); // 假设res.data是JSON字符串
			if (data.is_finish) {
				// 如果finish为true，表示消息完成
				messages.value.push({
					content: tempMessage.value + data.message.content, // 添加完整消息内容
					type: 'server'
				});
				tempMessage.value = ''; // 清空临时消息
			} else {
				// 如果finish为false，更新临时消息
				tempMessage.value += data.message.content;
			}
			// nextTick(scrollToBottom);
		});

		ws.value.onClose((res) => {
			console.log('WebSocket已关闭', res);
			socketConnected.value = false;
		});

		ws.value.onError((res) => {
			console.log('WebSocket发生错误', res);
			socketConnected.value = false;
		});
	};

	const sendMessage = () => {
		if (!socketConnected.value) {
			attemptReconnect()
		}
		if (socketConnected.value) {
			if (inputMessage.value !== '') {
				const userMessage = inputMessage.value;
				messages.value.push({
					content: userMessage,
					type: 'user'
				});

				ws.value.send({
					data: userMessage,
					success: () => {
						console.log('消息发送成功');
					},
					fail: (error) => {
						console.error('消息发送失败', error);
					}
				});
				inputMessage.value = '';
			}
		} else {
			console.log('WebSocket连接未打开');
		}
	};

	const attemptReconnect = () => {
		if (reconnectAttempts.value < 3) { // 限制重连次数
			console.log(`尝试重新连接...（第 ${reconnectAttempts.value + 1} 次）`);
			reconnectAttempts.value += 1;
			setTimeout(() => {
				initWebSocket(); // 再次尝试连接
			}, 2000); // 每次尝试之间的等待时间
		} else {
			console.log('重连次数已达上限，停止重连。');
		}
	};

	onMounted(() => {
		initWebSocket();
	});

	onUnmounted(() => {
		if (ws.value) {
			ws.value.close();
		}
	});
</script>

<style scoped lang="scss">
	.container {
		width: 100%;
		display: flex;
		flex-direction: column;

		/* #ifdef H5 */
		height: calc(100vh - 85rpx);
		/* #endif */
		/* #ifndef H5 */
		height: 100vh;
		/* #endif */

		box-sizing: border-box;
		position: relative;

		.chat-box {
			flex: 1;
			overflow-y: auto;
			margin-bottom: 10rpx;
			background-color: #f5f5f5;
			padding: 10rpx;
			border-radius: 5px;

			.message {
				display: flex;
				flex-direction: column;
				margin-bottom: 10rpx;

				.user-message {
					align-self: flex-end;
					background-color: #dcf8c6;
					color: #000;
					padding: 10rpx;
					border-radius: 10rpx 10rpx 0 10rpx;
					max-width: 80%;
					word-wrap: break-word;
				}

				.server-message {
					align-self: flex-start;
					background-color: #ffffff;
					color: #000;
					padding: 10rpx;
					border-radius: 10rpx 10rpx 10rpx 0;
					max-width: 80%;
					word-wrap: break-word;
				}
			}
		}

		.input-container {
			display: flex;
			align-items: center;
			// position: fixed;
			// left: 0;
			// right: 0;
			// bottom: 100rpx;
			// /* 固定在底部 */
			// padding: 10rpx;
			// z-index: 999;

			.input-box {
				flex: 1;
				height: 50px;
				font-size: 16px;
				padding: 10px;
				box-sizing: border-box;
				border: 1px solid #ccc;
				border-radius: 5px 0 0 5px;
			}

			.send-button {
				height: 50px;
				font-size: 16px;
				padding: 0 20px;
				border: 1px solid #ccc;
				border-left: 0;
				border-radius: 0 5px 5px 0;
				background-color: #007bff;
				color: white;
				cursor: pointer;
			}

			.send-button:hover {
				background-color: #0056b3;
			}
		}
	}
</style>